package net.guoyixian.admin.service;

import net.guoyixian.admin.mapper.UserMapper;
import net.guoyixian.admin.pojo.Store;
import net.guoyixian.admin.pojo.User;
import net.guoyixian.common.datasource.DataSource;
import net.guoyixian.common.datasource.DataSource.SourceType;
import net.guoyixian.common.redis.RedisService;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * 用户service
 * 
 */
@Service
public class UserService {
	private static final ObjectMapper objectMapper = new ObjectMapper();
	private static final String TICKET = "TICKET";
	private static final ObjectMapper MAPPER = new ObjectMapper();
	private static final Integer TICKET_TIME = 60 * 60 * 2;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RedisService redisService;

	/**
	 * 用户登录
	 * 
	 * @param user
	 */
	public User queryByUsernameAndPassword(User user) {
		String password = DigestUtils.md5Hex(user.getPassword());
		user.setPassword(password);

		return userMapper.queryByUsernameAndPassword(user);
	}

	/**
	 * 登录检查用户名密码
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public String queryByUsername(String username, String password) {
		User user = userMapper.queryByUsername(username);

		// 比对密码是否正确
		if (null == user || !StringUtils.equals(user.getPassword(), DigestUtils.md5Hex(password))) {
			return null;
		}
		String ticket = DigestUtils.md5Hex(System.currentTimeMillis() + username + user.getId());
		try {
			// 将用户信息写入redis中，用于缓存共享
			this.redisService.set(TICKET + "_" + ticket, MAPPER.writeValueAsString(user), TICKET_TIME);
			return ticket;
		} catch (JsonProcessingException e) {
			// thorws new Exception();
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 登录检查用户名密码
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public void logout(String ticket) {
		this.redisService.del(ticket);
	}

	/**
	 * 查询用户数据
	 * 
	 * @param ticket
	 * @return
	 */
	public String queryUserByTicket(String ticket) {
		String key = TICKET + "_" + ticket;
		String data = this.redisService.get(key);
		if (data == null) {
			return null;
		}
		// 刷新数据的生存时间
		this.redisService.expire(key, TICKET_TIME);
		return data;
	}

	public void saveUser(User user) {
		userMapper.save(user);
	}

	@DataSource(SourceType.SLAVE)
	public PageList<Store> queryList(PageBounds bounds, String username, String realname) {
		return userMapper.queryList(bounds, username, realname);
	};
}
